using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.IO;
using System.Reflection;

namespace Phoenix
{
	public class DBUpdate
	{
		
		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main( string[] args) 
		{
			DialogResult res = MessageBox.Show("Please be sure you are logged under user account with Administrator privileges", "Phoenix Updater", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
			if(res == DialogResult.Cancel) 
				return;

			res = MessageBox.Show("Update process can require some time. Please wait until another message is appeared. Continue?", "Phoenix Updater", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
			if(res == DialogResult.No) 
				return;

			DBUpdate updater = new DBUpdate();
			try
			{
				updater.Update();
				MessageBox.Show("The database was updated successfully", "Phoenix Updater", MessageBoxButtons.OK, MessageBoxIcon.Information);
			}
			catch(Exception ex)
			{
				MessageBox.Show(ex.Message, "Phoenix Updater", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		private void Update()
		{
			System.Reflection.Assembly myAssembly = System.Reflection.Assembly.GetExecutingAssembly();
			StreamReader sr = new StreamReader(myAssembly.GetManifestResourceStream("Phoenix.scripts.def"));			
			string filename;
			while((filename = sr.ReadLine())!=null)
			{
				ExecuteScriptFile(filename);
			}	

		}

		private string GetConnectionString()
		{
			return string.Format("server={0};database={1}; Integrated Security=SSPI", @"(local)\Phoenix", "Phoenix");
		}

		private void ExecuteScriptFile(string filename)
		{
			SqlConnection conn  =  new SqlConnection(GetConnectionString());
			SqlCommand command= new SqlCommand();
			command.Connection = conn;
			string dbcommand = "";
			string line;
			
			Assembly myAssembly = System.Reflection.Assembly.GetExecutingAssembly();			

			StreamReader sr = new StreamReader(myAssembly.GetManifestResourceStream("Phoenix."+filename));						
				conn.Open();
				while((line = sr.ReadLine())!=null)
				{				
					
					if (line!="go" && line!="GO")
					{
						if (!line.StartsWith("--") && line!="")
							dbcommand+=line+"\n";
					}
					else
					{
						
							if (dbcommand!="")
							{
								command.CommandText = dbcommand;									
								command.ExecuteNonQuery();							
							}
						dbcommand="";
					}
			
				}

				if (dbcommand!="")
				{
					command.CommandText = dbcommand;									
					command.ExecuteNonQuery();
				}
				conn.Close();
			
		}

	}
}
